package com.sts.source.impl;

import cn.hutool.core.util.StrUtil;
import com.sts.source.StsSource;
import com.sts.source.model.TextSourceConfig;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;

@Slf4j
public class TextSourceImpl implements StsSource {

    private Stream<String> textReader;
    private final TextSourceConfig textSourceConfig;

    public TextSourceImpl(TextSourceConfig textSourceConfig) {
        this.textSourceConfig = textSourceConfig;
    }

    @Override
    public List<String> getHeader() {
        if (!textSourceConfig.isHasHeader()) {
            // false: 文件没有头，用指定的头
            return textSourceConfig.getHeaderList();
        }

        try (Stream<String> textReader = buildTextReader()) {
            String firstLine = textReader
                    .findFirst()
                    .orElseThrow(() -> new RuntimeException("文件为空"));

            return StrUtil.split(firstLine, textSourceConfig.getFieldSeparator());
        }
    }

    @Override
    public Stream<List<String>> getDataStream() {
        textReader = buildTextReader();

        if (textSourceConfig.isHasHeader()) {
            // true: 文件有头，需要跳过第一行头数据
            textReader = textReader.skip(1);
        }
        return textReader
                .map(line -> StrUtil.split(line, textSourceConfig.getFieldSeparator()));
    }

    @Override
    public void close() throws Exception {
        if (textReader != null) {
            textReader.close();
            log.info("TextReader Closed");
        }
    }

    private Stream<String> buildTextReader() {
        try {
            return Files.lines(Paths.get(textSourceConfig.getFilePath()));
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}
